package cn.hesion.thread.futureandpromise;
/**
 * ClassName: NettyFutureDemo <br/>
 * Description: <br/>
 * date: 2022/4/30 14:24<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

/**
 * NetttFuture的Demo
 * @author: hesion
 * @create: 2022-04-30 14:24
 **/
public class NettyFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long l = System.currentTimeMillis();
        DefaultEventExecutorGroup group = new DefaultEventExecutorGroup(4);
        Future<Integer> nettyFuture = group.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("执行耗时操作.....");
                timeConsumingOperation();
                return 100;
            }
        });
        nettyFuture.addListener(new FutureListener<Object>(){

            @Override
            public void operationComplete(Future<Object> objectFuture) throws Exception {
                System.out.println("计算结果:"+objectFuture.get());
            }
        });

        System.out.println("主线程运行耗时:"+(System.currentTimeMillis()-l));
        new CountDownLatch(1).await();
    }

    private static void timeConsumingOperation() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
